import router, { authRouter } from './index'
import useTagsViewStore from '@/store/modules/tagsView'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { getToken, setToken, setUser } from '@/utils/auth'

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  let token = getToken()

  //url token auto login
  const qToken = to.query.token
  if (qToken) {
    token = qToken
    setToken(qToken)
    /*const config = { headers: { 'Authentication': qToken } }
    // @ts-ignore
    const res = await ((await fetch('api/adminUser/info', config)).json())
    if (res.data != null) {
      token = qToken
      setToken(qToken)
      setUser(JSON.stringify(res.data))
      const auths = authRouter()
      authRouter().forEach(n => router.addRoute(n))
    }*/
  }

  if (token) { //token存在
    // 添加标签视图（不在登录页且有name）
    if (to.name) {
      try { useTagsViewStore().addView(to) } catch (e) { /* ignore */ }
    }
    if (to.query.token) {
      //delete to.query.token
      //next({ path: to.path, query: to.query })
      next()
    }
    else {
      switch (to.path) {
        case '/login':
          next({ path: '/' })
          break 
        default:
          next()
      }
    }
  }
  else {
    const whiteList = ['/login'] // 不重定向白名单
    whiteList.includes(to.path) ? next() : next('/login')
  }

  NProgress.done()
})

router.afterEach((to) => {
  try { useTagsViewStore().addCachedView(to) } catch (e) { /* ignore */ }
  NProgress.done() // 结束Progress
})
